import { useEffect, useState } from 'react'
import { useParams } from 'react-router-dom'
import { Row, Col, List, Card } from 'antd'
import { PlayCircleOutlined } from '@ant-design/icons'
import { courseService } from '../../services'

const CoursePlayer = () => {
  const { id } = useParams()
  const [course, setCourse] = useState<any>(null)
  const [currentLesson, setCurrentLesson] = useState<any>(null)

  useEffect(() => {
    if (id) {
      loadCourse()
    }
  }, [id])

  const loadCourse = async () => {
    try {
      const response: any = await courseService.getCourseById(id!)
      if (response.code === 200) {
        setCourse(response.data)
        // 设置第一个课程为当前课程
        if (response.data.chapters?.length > 0 && response.data.chapters[0].lessons?.length > 0) {
          setCurrentLesson(response.data.chapters[0].lessons[0])
        }
      }
    } catch (error) {
      console.error('Load course error:', error)
    }
  }

  const handleLessonClick = (lesson: any) => {
    setCurrentLesson(lesson)
    // 更新学习进度
    updateProgress(lesson.id)
  }

  const updateProgress = async (lessonId: string) => {
    try {
      await courseService.updateProgress(lessonId, {
        watchedDuration: 0,
        lastPosition: 0,
        isCompleted: false,
      })
    } catch (error) {
      console.error('Update progress error:', error)
    }
  }

  return (
    <div style={{ height: 'calc(100vh - 64px)', display: 'flex' }}>
      <div style={{ flex: 1, background: '#000', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
        {currentLesson?.videoUrl ? (
          <video
            key={currentLesson.id}
            controls
            style={{ width: '100%', maxHeight: '100%' }}
            src={currentLesson.videoUrl}
          >
            您的浏览器不支持视频播放
          </video>
        ) : (
          <div style={{ color: '#fff', fontSize: '24px' }}>
            <PlayCircleOutlined style={{ fontSize: '80px', marginBottom: '16px', display: 'block' }} />
            {currentLesson ? '暂无视频' : '请选择课程'}
          </div>
        )}
      </div>

      <div style={{ width: '400px', background: '#fff', overflow: 'auto' }}>
        <Card title={course?.title} bordered={false}>
          {course?.chapters?.map((chapter: any) => (
            <div key={chapter.id} style={{ marginBottom: '16px' }}>
              <h4>{chapter.title}</h4>
              <List
                size="small"
                dataSource={chapter.lessons || []}
                renderItem={(lesson: any) => (
                  <List.Item
                    style={{
                      cursor: 'pointer',
                      background: currentLesson?.id === lesson.id ? '#e6f7ff' : 'transparent',
                    }}
                    onClick={() => handleLessonClick(lesson)}
                  >
                    <PlayCircleOutlined style={{ marginRight: '8px' }} />
                    {lesson.title}
                  </List.Item>
                )}
              />
            </div>
          ))}
        </Card>
      </div>
    </div>
  )
}

export default CoursePlayer
